 package implementation.gambiarra;

import genericServer.server.CoresAutodetect;

import java.io.File;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

import entility.Job;
import entility.Machine;


public class ClientController extends Thread {
	
	
	public static SendFiles[] threads;
	public static Queue<Job> jobs;
	public int threadSize;
	private boolean working;
	public int checkNumber = 0;
	public int timeOutToCheck;
	public int lastJobSizeSended = 0;
	
	

	public static ClientController uniqueInstance;

	private ClientController(int threadSize, int timeOutCheck) {
	
		
		// TODO Auto-generated constructor stub
		setPriority(8);
		threads =  new SendFiles[threadSize];
		jobs = new ConcurrentLinkedQueue<Job>();
		this.threadSize = threadSize;
		this.setWorking(false); 
		for(int i=0; i<this.threadSize; i++)
		{
			SendFiles t = new SendFiles();
			threads[i] = t;
		}

		this.timeOutToCheck = timeOutCheck;
		
	}

	public void add(Job job) {
		
		setPriority(3);
		jobs.offer(job);
		//System.out.println(jobs);
		


	}




	private void check() {
		// TODO Auto-generated method stub
		
		System.out.println(this.getNumberOfJobs());
		try 
		{
			
			for(int i = 0; i< this.threadSize; i++)
			{
				if(!threads[i].isWorking && jobs.size() > 0)
				{
					Job job = jobs.poll();
					
					threads[i] = new SendFiles(new Machine(job.getData().get(0)),new File(job.getData().get(1).trim()));
					threads[i].start();
				}
			}
			
			

			
		}
		catch(Exception e)
		{
			System.out.println("Recorey Server");
			e.printStackTrace();
			
		}
		finally{
			
			try {
				sleep(this.timeOutToCheck);
				this.check();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
	}


	public void run()
	{
		this.check();
	}


	public int getNumberOfJobs()
	{

		int jobsinthread = 0;

		for(SendFiles t : threads)
		{

			if(t.isWorking)
				jobsinthread++;
		}

		return jobsinthread+jobs.size();
	}


	public int getNumberOfJobsWaiting()
	{
		return jobs.size();
	}


	public boolean isWorking() {
		return working;
	}


	public void setWorking(boolean working) {
		this.working = working;
	}


	public static ClientController getInstance() {

		if(uniqueInstance == null)
		{
			int numberOfThreads = CoresAutodetect.detect();
			ClientController newJobController = new ClientController(numberOfThreads, 1000);
			uniqueInstance = newJobController;
		}
		// TODO Auto-generated method stub
		return uniqueInstance;
	}

	

}
